<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
        "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="../Styles/style.css" rel="stylesheet" type="text/css"/>


</head>

<body>
<div class="article-body">

    <div class="article-intro" id="content">

        <h1>Python3 函数</h1>
        <p>函数是组织好的，可重复使用的，用来实现单一，或相关联功能的代码段。</p>
        <p>函数能提高应用的模块性，和代码的重复利用率。你已经知道Python提供了许多内建函数，比如print()。但你也可以自己创建函数，这被叫做用户自定义函数。</p>

        <h2>定义一个函数</h2>

        <p>你可以定义一个由自己想要功能的函数，以下是简单的规则：</p>
        <ul>
            <li>函数代码块以 <b>def</b> 关键词开头，后接函数标识符名称和圆括号 <b>()</b>。</li>

            <li>任何传入参数和自变量必须放在圆括号中间，圆括号之间可以用于定义参数。</li>

            <li>函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。</li>

            <li>函数内容以冒号起始，并且缩进。</li>

            <li><strong>return [表达式]</strong> 结束函数，选择性地返回一个值给调用方。不带表达式的return相当于返回 None。</li>
        </ul>

        <h3>语法</h3>
        <p>Python 定义函数使用 def 关键字，一般格式如下：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="kwd">def</span><span class="pln"> </span><span
                class="pun">函数名（参数列表）:</span><span class="pln">
    </span><span class="pun">函数体</span></pre>

        <p>默认情况下，参数值和参数名称是按函数声明中定义的的顺序匹配起来的。</p>
        <h3>实例</h3>
        <p>让我们使用函数来输出"Hello World！"：</p>

        <pre class="prettyprint prettyprinted" style=""><span class="pun">&gt;&gt;&gt;</span><span
                class="pln"> </span><span class="kwd">def</span><span class="pln"> hello</span><span
                class="pun">()</span><span class="pln"> </span><span class="pun">:</span><span class="pln">
   </span><span class="kwd">print</span><span class="pun">(</span><span class="str">"Hello World!"</span><span
                class="pun">)</span><span class="pln">


</span><span class="pun">&gt;&gt;&gt;</span><span class="pln"> hello</span><span class="pun">()</span><span class="pln">
</span><span class="typ">Hello</span><span class="pln"> </span><span class="typ">World</span><span
                class="pun">!</span><span class="pln">
</span><span class="pun">&gt;&gt;&gt;</span><span class="pln"> </span></pre>
        <p>
            更复杂点的应用，函数中带上参数变量:</p>
        <pre class="prettyprint prettyprinted" style=""><span class="com">#!/usr/bin/python3</span><span class="pln">

</span><span class="com"># 计算面积函数</span><span class="pln">
</span><span class="kwd">def</span><span class="pln"> area</span><span class="pun">(</span><span
                class="pln">width</span><span class="pun">,</span><span class="pln"> height</span><span
                class="pun">):</span><span class="pln">
    </span><span class="kwd">return</span><span class="pln"> width </span><span class="pun">*</span><span class="pln"> height

</span><span class="kwd">def</span><span class="pln"> print_welcome</span><span class="pun">(</span><span class="pln">name</span><span
                class="pun">):</span><span class="pln">
    </span><span class="kwd">print</span><span class="pun">(</span><span class="str">"Welcome"</span><span
                class="pun">,</span><span class="pln"> name</span><span class="pun">)</span><span class="pln">

print_welcome</span><span class="pun">(</span><span class="str">"Runoob"</span><span class="pun">)</span><span
                class="pln">
w </span><span class="pun">=</span><span class="pln"> </span><span class="lit">4</span><span class="pln">
h </span><span class="pun">=</span><span class="pln"> </span><span class="lit">5</span><span class="pln">
</span><span class="kwd">print</span><span class="pun">(</span><span class="str">"width ="</span><span
                class="pun">,</span><span class="pln"> w</span><span class="pun">,</span><span class="pln"> </span><span
                class="str">" height ="</span><span class="pun">,</span><span class="pln"> h</span><span
                class="pun">,</span><span class="pln"> </span><span class="str">" area ="</span><span
                class="pun">,</span><span class="pln"> area</span><span class="pun">(</span><span
                class="pln">w</span><span class="pun">,</span><span class="pln"> h</span><span
                class="pun">))</span></pre>
        <p>以上实例输出结果：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="typ">Welcome</span><span class="pln"> </span><span
                class="typ">Runoob</span><span class="pln">
width </span><span class="pun">=</span><span class="pln"> </span><span class="lit">4</span><span
                class="pln">  height </span><span class="pun">=</span><span class="pln"> </span><span
                class="lit">5</span><span class="pln">  area </span><span class="pun">=</span><span class="pln"> </span><span
                class="lit">20</span></pre>

        <h2>函数调用</h2>
        <p>定义一个函数：给了函数一个名称，指定了函数里包含的参数，和代码块结构。</p>

        <p>这个函数的基本结构完成以后，你可以通过另一个函数调用执行，也可以直接从 Python 命令提示符执行。</p>

        <p>如下实例调用了 <strong>printme()</strong> 函数：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="com">#!/usr/bin/python3</span><span class="pln">

</span><span class="com"># 定义函数</span><span class="pln">
</span><span class="kwd">def</span><span class="pln"> printme</span><span class="pun">(</span><span
                class="pln"> str </span><span class="pun">):</span><span class="pln">
   </span><span class="str">"打印任何传入的字符串"</span><span class="pln">
   </span><span class="kwd">print</span><span class="pln"> </span><span class="pun">(</span><span class="pln">str</span><span
                class="pun">);</span><span class="pln">
   </span><span class="kwd">return</span><span class="pun">;</span><span class="pln">

</span><span class="com"># 调用函数</span><span class="pln">
printme</span><span class="pun">(</span><span class="str">"我要调用用户自定义函数!"</span><span class="pun">);</span><span
                class="pln">
printme</span><span class="pun">(</span><span class="str">"再次调用同一函数"</span><span class="pun">);</span></pre>
        <p>以上实例输出结果：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="pun">我要调用用户自定义函数!</span><span class="pln">
</span><span class="pun">再次调用同一函数</span></pre>

        <h2>参数传递</h2>
        <p>在 python 中，类型属于对象，变量是没有类型的：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="pln">a</span><span class="pun">=[</span><span
                class="lit">1</span><span class="pun">,</span><span class="lit">2</span><span class="pun">,</span><span
                class="lit">3</span><span class="pun">]</span><span class="pln">

a</span><span class="pun">=</span><span class="str">"Runoob"</span></pre>
        <p>以上代码中，<b>[1,2,3]</b> 是 List 类型，<b>"Runoob"</b> 是 String 类型，而变量 a 是没有类型，她仅仅是一个对象的引用（一个指针），可以是 List 类型对象，也可以指向
            String 类型对象。</p>
        <h3>可更改(mutable)与不可更改(immutable)对象</h3>
        <p>在 python 中，strings, tuples, 和 numbers 是不可更改的对象，而 list,dict 等则是可以修改的对象。</p>
        <ul>
            <li><p><b>
                不可变类型：</b>变量赋值 <b>a=5</b> 后再赋值 <b>a=10</b>，这里实际是新生成一个 int 值对象 10，再让 a 指向它，而 5 被丢弃，不是改变a的值，相当于新生成了a。</p>
            </li>
            <li><p><b>
                可变类型：</b>变量赋值 <b>la=[1,2,3,4]</b> 后再赋值 <b>la[2]=5</b> 则是将 list la 的第三个元素值更改，本身la没有动，只是其内部的一部分值被修改了。</p>
            </li>
        </ul>
        <p>python 函数的参数传递：</p>
        <ul>
            <li><p><b>
                不可变类型：</b>类似 c++ 的值传递，如 整数、字符串、元组。如fun（a），传递的只是a的值，没有影响a对象本身。比如在 fun（a）内部修改 a 的值，只是修改另一个复制的对象，不会影响 a 本身。
            </p></li>
            <li><p><b>
                可变类型：</b>类似 c++ 的引用传递，如 列表，字典。如 fun（la），则是将 la 真正的传过去，修改后fun外部的la也会受影响</p></li>
        </ul>
        <p>python 中一切都是对象，严格意义我们不能说值传递还是引用传递，我们应该说传不可变对象和传可变对象。</p>
        <h3>python 传不可变对象实例</h3>
        <pre class="prettyprint prettyprinted" style=""><span class="com">#!/usr/bin/python3</span><span class="pln">

</span><span class="kwd">def</span><span class="pln"> </span><span class="typ">ChangeInt</span><span
                class="pun">(</span><span class="pln"> a </span><span class="pun">):</span><span class="pln">
    a </span><span class="pun">=</span><span class="pln"> </span><span class="lit">10</span><span class="pln">

b </span><span class="pun">=</span><span class="pln"> </span><span class="lit">2</span><span class="pln">
</span><span class="typ">ChangeInt</span><span class="pun">(</span><span class="pln">b</span><span
                class="pun">)</span><span class="pln">
</span><span class="kwd">print</span><span class="pun">(</span><span class="pln"> b </span><span
                class="pun">)</span><span class="pln"> </span><span class="com"># 结果是 2</span></pre>
        <p>实例中有 int 对象 2，指向它的变量是 b，在传递给 ChangeInt 函数时，按传值的方式复制了变量 b，a 和 b 都指向了同一个 Int 对象，在 a=10 时，则新生成一个 int 值对象 10，并让 a
            指向它。</p>
        <h3>传可变对象实例</h3>


        <p>可变对象在函数里修改了参数，那么在调用这个函数的函数里，原始的参数也被改变了。例如：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="com">#!/usr/bin/python3</span><span class="pln">

</span><span class="com"># 可写函数说明</span><span class="pln">
</span><span class="kwd">def</span><span class="pln"> changeme</span><span class="pun">(</span><span
                class="pln"> mylist </span><span class="pun">):</span><span class="pln">
   </span><span class="str">"修改传入的列表"</span><span class="pln">
   mylist</span><span class="pun">.</span><span class="pln">append</span><span class="pun">([</span><span
                class="lit">1</span><span class="pun">,</span><span class="lit">2</span><span class="pun">,</span><span
                class="lit">3</span><span class="pun">,</span><span class="lit">4</span><span
                class="pun">]);</span><span class="pln">
   </span><span class="kwd">print</span><span class="pln"> </span><span class="pun">(</span><span
                class="str">"函数内取值: "</span><span class="pun">,</span><span class="pln"> mylist</span><span class="pun">)</span><span
                class="pln">
   </span><span class="kwd">return</span><span class="pln">

</span><span class="com"># 调用changeme函数</span><span class="pln">
mylist </span><span class="pun">=</span><span class="pln"> </span><span class="pun">[</span><span
                class="lit">10</span><span class="pun">,</span><span class="lit">20</span><span
                class="pun">,</span><span class="lit">30</span><span class="pun">];</span><span class="pln">
changeme</span><span class="pun">(</span><span class="pln"> mylist </span><span class="pun">);</span><span class="pln">
</span><span class="kwd">print</span><span class="pln"> </span><span class="pun">(</span><span
                class="str">"函数外取值: "</span><span class="pun">,</span><span class="pln"> mylist</span><span class="pun">)</span></pre>
        <p>传入函数的和在末尾添加新内容的对象用的是同一个引用。故输出结果如下：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="pun">函数内取值:</span><span class="pln">  </span><span
                class="pun">[</span><span class="lit">10</span><span class="pun">,</span><span class="pln"> </span><span
                class="lit">20</span><span class="pun">,</span><span class="pln"> </span><span
                class="lit">30</span><span class="pun">,</span><span class="pln"> </span><span class="pun">[</span><span
                class="lit">1</span><span class="pun">,</span><span class="pln"> </span><span class="lit">2</span><span
                class="pun">,</span><span class="pln"> </span><span class="lit">3</span><span class="pun">,</span><span
                class="pln"> </span><span class="lit">4</span><span class="pun">]]</span><span class="pln">
</span><span class="pun">函数外取值:</span><span class="pln">  </span><span class="pun">[</span><span
                class="lit">10</span><span class="pun">,</span><span class="pln"> </span><span
                class="lit">20</span><span class="pun">,</span><span class="pln"> </span><span
                class="lit">30</span><span class="pun">,</span><span class="pln"> </span><span class="pun">[</span><span
                class="lit">1</span><span class="pun">,</span><span class="pln"> </span><span class="lit">2</span><span
                class="pun">,</span><span class="pln"> </span><span class="lit">3</span><span class="pun">,</span><span
                class="pln"> </span><span class="lit">4</span><span class="pun">]]</span></pre>

        <h2>参数</h2>
        <p>以下是调用函数时可使用的正式参数类型：</p>
        <ul>
            <li>必需参数</li>

            <li>关键字参数</li>

            <li>默认参数</li>

            <li>不定长参数</li>
        </ul>
        <h3>必需参数</h3>

        <p>必需参数须以正确的顺序传入函数。调用时的数量必须和声明时的一样。</p>

        <p>调用printme()函数，你必须传入一个参数，不然会出现语法错误：</p>

        <pre class="prettyprint prettyprinted" style=""><span class="com">#!/usr/bin/python3</span><span class="pln">

</span><span class="com">#可写函数说明</span><span class="pln">
</span><span class="kwd">def</span><span class="pln"> printme</span><span class="pun">(</span><span
                class="pln"> str </span><span class="pun">):</span><span class="pln">
   </span><span class="str">"打印任何传入的字符串"</span><span class="pln">
   </span><span class="kwd">print</span><span class="pln"> </span><span class="pun">(</span><span class="pln">str</span><span
                class="pun">);</span><span class="pln">
   </span><span class="kwd">return</span><span class="pun">;</span><span class="pln">

</span><span class="com">#调用printme函数</span><span class="pln">
printme</span><span class="pun">();</span></pre>
        <p>以上实例输出结果：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="typ">Traceback</span><span
                class="pln"> </span><span class="pun">(</span><span class="pln">most recent call </span><span
                class="kwd">last</span><span class="pun">):</span><span class="pln">
  </span><span class="typ">File</span><span class="pln"> </span><span class="str">"test.py"</span><span
                class="pun">,</span><span class="pln"> line </span><span class="lit">10</span><span class="pun">,</span><span
                class="pln"> </span><span class="kwd">in</span><span class="pln"> </span><span class="str">&lt;module&gt;</span><span
                class="pln">
    printme</span><span class="pun">();</span><span class="pln">
</span><span class="typ">TypeError</span><span class="pun">:</span><span class="pln"> printme</span><span
                class="pun">()</span><span class="pln"> missing </span><span class="lit">1</span><span class="pln"> required positional argument</span><span
                class="pun">:</span><span class="pln"> </span><span class="str">'str'</span></pre>
        <h3>关键字参数</h3>

        <p>关键字参数和函数调用关系紧密，函数调用使用关键字参数来确定传入的参数值。</p>
        <p>使用关键字参数允许函数调用时参数的顺序与声明时不一致，因为 Python 解释器能够用参数名匹配参数值。</p>
        <p>以下实例在函数 printme() 调用时使用参数名：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="com">#!/usr/bin/python3</span><span class="pln">

</span><span class="com">#可写函数说明</span><span class="pln">
</span><span class="kwd">def</span><span class="pln"> printme</span><span class="pun">(</span><span
                class="pln"> str </span><span class="pun">):</span><span class="pln">
   </span><span class="str">"打印任何传入的字符串"</span><span class="pln">
   </span><span class="kwd">print</span><span class="pln"> </span><span class="pun">(</span><span class="pln">str</span><span
                class="pun">);</span><span class="pln">
   </span><span class="kwd">return</span><span class="pun">;</span><span class="pln">

</span><span class="com">#调用printme函数</span><span class="pln">
printme</span><span class="pun">(</span><span class="pln"> str </span><span class="pun">=</span><span
                class="pln"> </span><span class="str">"菜鸟教程"</span><span class="pun">);</span></pre>
        <p>以上实例输出结果：
        </p>
        <pre class="prettyprint prettyprinted" style=""><span class="pun">菜鸟教程</span></pre>
        <p>以下实例中演示了函数参数的使用不需要使用指定顺序：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="com">#!/usr/bin/python3</span><span class="pln">

</span><span class="com">#可写函数说明</span><span class="pln">
</span><span class="kwd">def</span><span class="pln"> printinfo</span><span class="pun">(</span><span
                class="pln"> name</span><span class="pun">,</span><span class="pln"> age </span><span
                class="pun">):</span><span class="pln">
   </span><span class="str">"打印任何传入的字符串"</span><span class="pln">
   </span><span class="kwd">print</span><span class="pln"> </span><span class="pun">(</span><span
                class="str">"名字: "</span><span class="pun">,</span><span class="pln"> name</span><span
                class="pun">);</span><span class="pln">
   </span><span class="kwd">print</span><span class="pln"> </span><span class="pun">(</span><span
                class="str">"年龄: "</span><span class="pun">,</span><span class="pln"> age</span><span
                class="pun">);</span><span class="pln">
   </span><span class="kwd">return</span><span class="pun">;</span><span class="pln">

</span><span class="com">#调用printinfo函数</span><span class="pln">
printinfo</span><span class="pun">(</span><span class="pln"> age</span><span class="pun">=</span><span
                class="lit">50</span><span class="pun">,</span><span class="pln"> name</span><span
                class="pun">=</span><span class="str">"runoob"</span><span class="pln"> </span><span
                class="pun">);</span></pre>
        <p>以上实例输出结果：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="pun">名字:</span><span class="pln">  runoob
</span><span class="pun">年龄:</span><span class="pln">  </span><span class="lit">50</span></pre>
        <h3>默认参数</h3>

        <p>调用函数时，如果没有传递参数，则会使用默认参数。以下实例中如果没有传入 age 参数，则使用默认值：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="com">#!/usr/bin/python3</span><span class="pln">

</span><span class="com">#可写函数说明</span><span class="pln">
</span><span class="kwd">def</span><span class="pln"> printinfo</span><span class="pun">(</span><span
                class="pln"> name</span><span class="pun">,</span><span class="pln"> age </span><span
                class="pun">=</span><span class="pln"> </span><span class="lit">35</span><span class="pln"> </span><span
                class="pun">):</span><span class="pln">
   </span><span class="str">"打印任何传入的字符串"</span><span class="pln">
   </span><span class="kwd">print</span><span class="pln"> </span><span class="pun">(</span><span
                class="str">"名字: "</span><span class="pun">,</span><span class="pln"> name</span><span
                class="pun">);</span><span class="pln">
   </span><span class="kwd">print</span><span class="pln"> </span><span class="pun">(</span><span
                class="str">"年龄: "</span><span class="pun">,</span><span class="pln"> age</span><span
                class="pun">);</span><span class="pln">
   </span><span class="kwd">return</span><span class="pun">;</span><span class="pln">

</span><span class="com">#调用printinfo函数</span><span class="pln">
printinfo</span><span class="pun">(</span><span class="pln"> age</span><span class="pun">=</span><span
                class="lit">50</span><span class="pun">,</span><span class="pln"> name</span><span
                class="pun">=</span><span class="str">"runoob"</span><span class="pln"> </span><span
                class="pun">);</span><span class="pln">
</span><span class="kwd">print</span><span class="pln"> </span><span class="pun">(</span><span class="str">"------------------------"</span><span
                class="pun">)</span><span class="pln">
printinfo</span><span class="pun">(</span><span class="pln"> name</span><span class="pun">=</span><span class="str">"runoob"</span><span
                class="pln"> </span><span class="pun">);</span></pre>
        <p>以上实例输出结果：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="pun">名字:</span><span class="pln">  runoob
</span><span class="pun">年龄:</span><span class="pln">  </span><span class="lit">50</span><span class="pln">
</span><span class="pun">------------------------</span><span class="pln">
</span><span class="pun">名字:</span><span class="pln">  runoob
</span><span class="pun">年龄:</span><span class="pln">  </span><span class="lit">35</span></pre>
        <h3>不定长参数</h3>

        <p>你可能需要一个函数能处理比当初声明时更多的参数。这些参数叫做不定长参数，和上述2种参数不同，声明时不会命名。基本语法如下：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="kwd">def</span><span
                class="pln"> functionname</span><span class="pun">([</span><span class="pln">formal_args</span><span
                class="pun">,]</span><span class="pln"> </span><span class="pun">*</span><span class="pln">var_args_tuple </span><span
                class="pun">):</span><span class="pln">
   </span><span class="str">"函数_文档字符串"</span><span class="pln">
   function_suite
   </span><span class="kwd">return</span><span class="pln"> </span><span class="pun">[</span><span class="pln">expression</span><span
                class="pun">]</span></pre>
        <p>加了星号（*）的变量名会存放所有未命名的变量参数。如果在函数调用时没有指定参数，它就是一个空元组。我们也可以不向函数传递未命名的变量。如下实例：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="com">#!/usr/bin/python3</span><span class="pln">

</span><span class="com"># 可写函数说明</span><span class="pln">
</span><span class="kwd">def</span><span class="pln"> printinfo</span><span class="pun">(</span><span
                class="pln"> arg1</span><span class="pun">,</span><span class="pln"> </span><span
                class="pun">*</span><span class="pln">vartuple </span><span class="pun">):</span><span class="pln">
   </span><span class="str">"打印任何传入的参数"</span><span class="pln">
   </span><span class="kwd">print</span><span class="pln"> </span><span class="pun">(</span><span
                class="str">"输出: "</span><span class="pun">)</span><span class="pln">
   </span><span class="kwd">print</span><span class="pln"> </span><span class="pun">(</span><span
                class="pln">arg1</span><span class="pun">)</span><span class="pln">
   </span><span class="kwd">for</span><span class="pln"> </span><span class="kwd">var</span><span
                class="pln"> </span><span class="kwd">in</span><span class="pln"> vartuple</span><span
                class="pun">:</span><span class="pln">
      </span><span class="kwd">print</span><span class="pln"> </span><span class="pun">(</span><span
                class="kwd">var</span><span class="pun">)</span><span class="pln">
   </span><span class="kwd">return</span><span class="pun">;</span><span class="pln">

</span><span class="com"># 调用printinfo 函数</span><span class="pln">
printinfo</span><span class="pun">(</span><span class="pln"> </span><span class="lit">10</span><span
                class="pln"> </span><span class="pun">);</span><span class="pln">
printinfo</span><span class="pun">(</span><span class="pln"> </span><span class="lit">70</span><span
                class="pun">,</span><span class="pln"> </span><span class="lit">60</span><span class="pun">,</span><span
                class="pln"> </span><span class="lit">50</span><span class="pln"> </span><span
                class="pun">);</span></pre>
        <p>以上实例输出结果：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="pun">输出:</span><span class="pln">
</span><span class="lit">10</span><span class="pln">
</span><span class="pun">输出:</span><span class="pln">
</span><span class="lit">70</span><span class="pln">
</span><span class="lit">60</span><span class="pln">
</span><span class="lit">50</span></pre>



        <h2>匿名函数</h2>

        <p>python 使用 lambda 来创建匿名函数。</p>
        <p>所谓匿名，意即不再使用 def 语句这样标准的形式定义一个函数。</p>
        <ul>

            <li>lambda 只是一个表达式，函数体比 def 简单很多。
            </li>
            <li>
                lambda的主体是一个表达式，而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。
            </li>
            <li>lambda 函数拥有自己的命名空间，且不能访问自己参数列表之外或全局命名空间里的参数。</li>

            <li>虽然lambda函数看起来只能写一行，却不等同于C或C++的内联函数，后者的目的是调用小函数时不占用栈内存从而增加运行效率。</li>
        </ul>
        <h3>语法</h3>

        <p>lambda 函数的语法只包含一个语句，如下：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="kwd">lambda</span><span class="pln"> </span><span
                class="pun">[</span><span class="pln">arg1 </span><span class="pun">[,</span><span
                class="pln">arg2</span><span class="pun">,.....</span><span class="pln">argn</span><span
                class="pun">]]:</span><span class="pln">expression</span></pre>
        <p>如下实例：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="com">#!/usr/bin/python3</span><span class="pln">

</span><span class="com"># 可写函数说明</span><span class="pln">
sum </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">lambda</span><span
                class="pln"> arg1</span><span class="pun">,</span><span class="pln"> arg2</span><span
                class="pun">:</span><span class="pln"> arg1 </span><span class="pun">+</span><span
                class="pln"> arg2</span><span class="pun">;</span><span class="pln">

</span><span class="com"># 调用sum函数</span><span class="pln">
</span><span class="kwd">print</span><span class="pln"> </span><span class="pun">(</span><span
                class="str">"相加后的值为 : "</span><span class="pun">,</span><span class="pln"> sum</span><span
                class="pun">(</span><span class="pln"> </span><span class="lit">10</span><span class="pun">,</span><span
                class="pln"> </span><span class="lit">20</span><span class="pln"> </span><span
                class="pun">))</span><span class="pln">
</span><span class="kwd">print</span><span class="pln"> </span><span class="pun">(</span><span
                class="str">"相加后的值为 : "</span><span class="pun">,</span><span class="pln"> sum</span><span
                class="pun">(</span><span class="pln"> </span><span class="lit">20</span><span class="pun">,</span><span
                class="pln"> </span><span class="lit">20</span><span class="pln"> </span><span
                class="pun">))</span></pre>
        <p>以上实例输出结果：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="pun">相加后的值为</span><span class="pln"> </span><span
                class="pun">:</span><span class="pln">  </span><span class="lit">30</span><span class="pln">
</span><span class="pun">相加后的值为</span><span class="pln"> </span><span class="pun">:</span><span
                class="pln">  </span><span class="lit">40</span></pre>


        <h2>return语句</h2>

        <p><b>return [表达式]</b> 语句用于退出函数，选择性地向调用方返回一个表达式。不带参数值的return语句返回None。之前的例子都没有示范如何返回数值，以下实例演示了 return 语句的用法：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="com">#!/usr/bin/python3</span><span class="pln">

</span><span class="com"># 可写函数说明</span><span class="pln">
</span><span class="kwd">def</span><span class="pln"> sum</span><span class="pun">(</span><span class="pln"> arg1</span><span
                class="pun">,</span><span class="pln"> arg2 </span><span class="pun">):</span><span class="pln">
   </span><span class="com"># 返回2个参数的和."</span><span class="pln">
   total </span><span class="pun">=</span><span class="pln"> arg1 </span><span class="pun">+</span><span class="pln"> arg2
   </span><span class="kwd">print</span><span class="pln"> </span><span class="pun">(</span><span
                class="str">"函数内 : "</span><span class="pun">,</span><span class="pln"> total</span><span
                class="pun">)</span><span class="pln">
   </span><span class="kwd">return</span><span class="pln"> total</span><span class="pun">;</span><span class="pln">

</span><span class="com"># 调用sum函数</span><span class="pln">
total </span><span class="pun">=</span><span class="pln"> sum</span><span class="pun">(</span><span class="pln"> </span><span
                class="lit">10</span><span class="pun">,</span><span class="pln"> </span><span
                class="lit">20</span><span class="pln"> </span><span class="pun">);</span><span class="pln">
</span><span class="kwd">print</span><span class="pln"> </span><span class="pun">(</span><span
                class="str">"函数外 : "</span><span class="pun">,</span><span class="pln"> total</span><span
                class="pun">)</span></pre>
        <p>以上实例输出结果：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="pun">函数内</span><span class="pln"> </span><span
                class="pun">:</span><span class="pln">  </span><span class="lit">30</span><span class="pln">
</span><span class="pun">函数外</span><span class="pln"> </span><span class="pun">:</span><span class="pln">  </span><span
                class="lit">30</span></pre>

        <h2>变量作用域</h2>

        <p>Python 中，程序的变量并不是在哪个位置都可以访问的，访问权限决定于这个变量是在哪里赋值的。</p>

        <p>变量的作用域决定了在哪一部分程序可以访问哪个特定的变量名称。Python的作用域一共有4种，分别是：</p>
        <ul>
            <li>L （Local） 局部作用域</li>
            <li>E （Enclosing） 闭包函数外的函数中</li>
            <li>G （Global） 全局作用域</li>
            <li>B （Built-in） 内建作用域</li>
        </ul>
        <p>以 L –&gt; E –&gt; G –&gt;B 的规则查找，即：在局部找不到，便会去局部外的局部找（例如闭包），再找不到就会去全局找，再者去内建中找。</p>
        <pre class="prettyprint prettyprinted" style=""><span class="pln">x </span><span class="pun">=</span><span
                class="pln"> </span><span class="kwd">int</span><span class="pun">(</span><span
                class="lit">2.9</span><span class="pun">)</span><span class="pln">  </span><span
                class="com"># 内建作用域</span><span class="pln">

g_count </span><span class="pun">=</span><span class="pln"> </span><span class="lit">0</span><span class="pln">  </span><span
                class="com"># 全局作用域</span><span class="pln">
</span><span class="kwd">def</span><span class="pln"> outer</span><span class="pun">():</span><span class="pln">
    o_count </span><span class="pun">=</span><span class="pln"> </span><span class="lit">1</span><span
                class="pln">  </span><span class="com"># 闭包函数外的函数中</span><span class="pln">
    </span><span class="kwd">def</span><span class="pln"> inner</span><span class="pun">():</span><span class="pln">
        i_count </span><span class="pun">=</span><span class="pln"> </span><span class="lit">2</span><span
                class="pln">  </span><span class="com"># 局部作用域</span></pre>
        <p>Python 中只有模块（module），类（class）以及函数（def、lambda）才会引入新的作用域，其它的代码块（如
            if/elif/else/、try/except、for/while等）是不会引入新的作用域的，也就是说这这些语句内定义的变量，外部也可以访问，如下代码：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="pun">&gt;&gt;&gt;</span><span
                class="pln"> </span><span class="kwd">if</span><span class="pln"> </span><span
                class="kwd">True</span><span class="pun">:</span><span class="pln">
</span><span class="pun">...</span><span class="pln">  msg </span><span class="pun">=</span><span
                class="pln"> </span><span class="str">'I am from Runoob'</span><span class="pln">
</span><span class="pun">...</span><span class="pln">
</span><span class="pun">&gt;&gt;&gt;</span><span class="pln"> msg
</span><span class="str">'I am from Runoob'</span><span class="pln">
</span><span class="pun">&gt;&gt;&gt;</span><span class="pln"> </span></pre>
        <p>实例中 msg 变量定义在 if 语句块中，但外部还是可以访问的。</p>
        <p>如果将 msg 定义在函数中，则它就是局部变量，外部不能访问：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="pun">&gt;&gt;&gt;</span><span
                class="pln"> </span><span class="kwd">def</span><span class="pln"> test</span><span
                class="pun">():</span><span class="pln">
</span><span class="pun">...</span><span class="pln">     msg_inner </span><span class="pun">=</span><span
                class="pln"> </span><span class="str">'I am from Runoob'</span><span class="pln">
</span><span class="pun">...</span><span class="pln">
</span><span class="pun">&gt;&gt;&gt;</span><span class="pln"> msg_inner
</span><span class="typ">Traceback</span><span class="pln"> </span><span class="pun">(</span><span class="pln">most recent call </span><span
                class="kwd">last</span><span class="pun">):</span><span class="pln">
  </span><span class="typ">File</span><span class="pln"> </span><span class="str">"&lt;stdin&gt;"</span><span
                class="pun">,</span><span class="pln"> line </span><span class="lit">1</span><span
                class="pun">,</span><span class="pln"> </span><span class="kwd">in</span><span class="pln"> </span><span
                class="str">&lt;module&gt;</span><span class="pln">
</span><span class="typ">NameError</span><span class="pun">:</span><span class="pln"> name </span><span class="str">'msg_inner'</span><span
                class="pln"> </span><span class="kwd">is</span><span class="pln"> </span><span
                class="kwd">not</span><span class="pln"> </span><span class="kwd">defined</span><span class="pln">
</span><span class="pun">&gt;&gt;&gt;</span><span class="pln"> </span></pre>
        <p>从报错的信息上看，说明了 msg_inner 未定义，无法使用，因为它是局部变量，只有在函数内可以使用。</p>

        <h3>全局变量和局部变量</h3>

        <p>定义在函数内部的变量拥有一个局部作用域，定义在函数外的拥有全局作用域。</p>

        <p>局部变量只能在其被声明的函数内部访问，而全局变量可以在整个程序范围内访问。调用函数时，所有在函数内声明的变量名称都将被加入到作用域中。如下实例：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="com">#!/usr/bin/python3</span><span class="pln">

total </span><span class="pun">=</span><span class="pln"> </span><span class="lit">0</span><span
                class="pun">;</span><span class="pln"> </span><span class="com"># 这是一个全局变量</span><span class="pln">
</span><span class="com"># 可写函数说明</span><span class="pln">
</span><span class="kwd">def</span><span class="pln"> sum</span><span class="pun">(</span><span class="pln"> arg1</span><span
                class="pun">,</span><span class="pln"> arg2 </span><span class="pun">):</span><span class="pln">
    </span><span class="com">#返回2个参数的和."</span><span class="pln">
    total </span><span class="pun">=</span><span class="pln"> arg1 </span><span class="pun">+</span><span class="pln"> arg2</span><span
                class="pun">;</span><span class="pln"> </span><span class="com"># total在这里是局部变量.</span><span
                class="pln">
    </span><span class="kwd">print</span><span class="pln"> </span><span class="pun">(</span><span class="str">"函数内是局部变量 : "</span><span
                class="pun">,</span><span class="pln"> total</span><span class="pun">)</span><span class="pln">
    </span><span class="kwd">return</span><span class="pln"> total</span><span class="pun">;</span><span class="pln">

</span><span class="com">#调用sum函数</span><span class="pln">
sum</span><span class="pun">(</span><span class="pln"> </span><span class="lit">10</span><span class="pun">,</span><span
                class="pln"> </span><span class="lit">20</span><span class="pln"> </span><span
                class="pun">);</span><span class="pln">
</span><span class="kwd">print</span><span class="pln"> </span><span class="pun">(</span><span
                class="str">"函数外是全局变量 : "</span><span class="pun">,</span><span class="pln"> total</span><span
                class="pun">)</span></pre>
        <p>以上实例输出结果：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="pun">函数内是局部变量</span><span class="pln"> </span><span
                class="pun">:</span><span class="pln">  </span><span class="lit">30</span><span class="pln">
</span><span class="pun">函数外是全局变量</span><span class="pln"> </span><span class="pun">:</span><span
                class="pln">  </span><span class="lit">0</span></pre>
        <h3>global 和 nonlocal关键字 </h3>
        <p>当内部作用域想修改外部作用域的变量时，就要用到global和nonlocal关键字了。</p>
        <p>以下实例修改全局变量 num：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="com">#!/usr/bin/python3</span><span class="pln">

num </span><span class="pun">=</span><span class="pln"> </span><span class="lit">1</span><span class="pln">
</span><span class="kwd">def</span><span class="pln"> fun1</span><span class="pun">():</span><span class="pln">
    </span><span class="kwd">global</span><span class="pln"> num  </span><span
                class="com"># 需要使用 global 关键字声明</span><span class="pln">
    </span><span class="kwd">print</span><span class="pun">(</span><span class="pln">num</span><span
                class="pun">)</span><span class="pln">
    num </span><span class="pun">=</span><span class="pln"> </span><span class="lit">123</span><span class="pln">
    </span><span class="kwd">print</span><span class="pun">(</span><span class="pln">num</span><span
                class="pun">)</span><span class="pln">
fun1</span><span class="pun">()</span><span class="pln">
</span></pre>
        <p>以上实例输出结果：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="lit">1</span><span class="pln">
</span><span class="lit">123</span></pre>
        <p>如果要修改嵌套作用域（enclosing 作用域，外层非全局作用域）中的变量则需要 nonlocal 关键字了，如下实例：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="com">#!/usr/bin/python3</span><span class="pln">

</span><span class="kwd">def</span><span class="pln"> outer</span><span class="pun">():</span><span class="pln">
    num </span><span class="pun">=</span><span class="pln"> </span><span class="lit">10</span><span class="pln">
    </span><span class="kwd">def</span><span class="pln"> inner</span><span class="pun">():</span><span class="pln">
        </span><span class="kwd">nonlocal</span><span class="pln"> num   </span><span class="com"># nonlocal关键字声明</span><span
                class="pln">
        num </span><span class="pun">=</span><span class="pln"> </span><span class="lit">100</span><span class="pln">
        </span><span class="kwd">print</span><span class="pun">(</span><span class="pln">num</span><span
                class="pun">)</span><span class="pln">
    inner</span><span class="pun">()</span><span class="pln">
    </span><span class="kwd">print</span><span class="pun">(</span><span class="pln">num</span><span
                class="pun">)</span><span class="pln">
outer</span><span class="pun">()</span></pre>
        <p>以上实例输出结果：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="lit">100</span><span class="pln">
</span><span class="lit">100</span></pre>
        <p>另外有一种特殊情况，假设下面这段代码被运行：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="com">#!/usr/bin/python3</span><span class="pln">

a </span><span class="pun">=</span><span class="pln"> </span><span class="lit">10</span><span class="pln">
</span><span class="kwd">def</span><span class="pln"> test</span><span class="pun">():</span><span class="pln">
    a </span><span class="pun">=</span><span class="pln"> a </span><span class="pun">+</span><span
                class="pln"> </span><span class="lit">1</span><span class="pln">
    </span><span class="kwd">print</span><span class="pun">(</span><span class="pln">a</span><span
                class="pun">)</span><span class="pln">
test</span><span class="pun">()</span></pre>

        <p>
            以上程序执行，报错信息如下：</p>
        <pre class="prettyprint prettyprinted" style=""><span class="typ">Traceback</span><span
                class="pln"> </span><span class="pun">(</span><span class="pln">most recent call </span><span
                class="kwd">last</span><span class="pun">):</span><span class="pln">
  </span><span class="typ">File</span><span class="pln"> </span><span class="str">"test.py"</span><span
                class="pun">,</span><span class="pln"> line </span><span class="lit">7</span><span
                class="pun">,</span><span class="pln"> </span><span class="kwd">in</span><span class="pln"> </span><span
                class="str">&lt;module&gt;</span><span class="pln">
    test</span><span class="pun">()</span><span class="pln">
  </span><span class="typ">File</span><span class="pln"> </span><span class="str">"test.py"</span><span
                class="pun">,</span><span class="pln"> line </span><span class="lit">5</span><span
                class="pun">,</span><span class="pln"> </span><span class="kwd">in</span><span class="pln"> test
    a </span><span class="pun">=</span><span class="pln"> a </span><span class="pun">+</span><span
                class="pln"> </span><span class="lit">1</span><span class="pln">
</span><span class="typ">UnboundLocalError</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">local</span><span
                class="pln"> variable </span><span class="str">'a'</span><span
                class="pln"> referenced before assignment</span></pre>
        <p>错误信息为局部作用域引用错误，因为 test 函数中的 a 使用的是局部，未定义，无法修改。</p>

    </div>
</div>
</body>
</html>
